package com.taobao.jingling.web.action;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.taobao.api.TaobaoApiException;
import com.taobao.api.TaobaoJsonRestClient;
import com.taobao.api.TaobaoRestClient;
import com.taobao.api.model.UserGetRequest;
import com.taobao.api.model.UserGetResponse;

public class GetUserProfile extends HttpServlet {

	private static final transient Log log = LogFactory.getLog(GetUserProfile.class);
	
	private static final long serialVersionUID = 1L;

	public GetUserProfile() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
            this.doPost(request, response);
		
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		     String appkey = "28097";
		     String secret = "42ff2240438d11deae718c0bea828c3d";
		     try {
				TaobaoRestClient client=new TaobaoJsonRestClient(appkey,secret);
				UserGetRequest userReq=new UserGetRequest().withNick("zhouxiaolino").withFields("nick,sex,location,created,lastVisit,buyerCredit,realName,idCard,phone,mobile,email,birthday");
				String sessionId=appkey;
				UserGetResponse userRes=client.userGet(userReq, sessionId);
				log.info(userRes.getBody());
				if(!userRes.isSuccess())	
				{
					if(userRes.isRedirect()){
						request.setAttribute("url", userRes.getRedirectUrl(URLEncoder.encode(request.getRequestURL().append('?').append("appkey=").append(appkey).append("&secret=").append(secret).toString(),"utf-8")));
					}else{
						request.setAttribute("msg", userRes.getMsg());
					}
				}else{
					request.setAttribute("user", userRes.getUser());
				}
			} catch (TaobaoApiException e) {
				throw new ServletException(e);
			}
			request.getRequestDispatcher("/getUserProfile.jsp").forward(request, response);
		
	}

	
	public void init() throws ServletException {
		// Put your code here
	}

}
